<template>
  <div class="learning-progress">
    <!-- 学习统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="stat-header">
              <el-icon><Reading /></el-icon>
              <span>在学课程</span>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.learningCourses }}</div>
            <div class="stat-label">门课程</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="stat-header">
              <el-icon><Timer /></el-icon>
              <span>学习时长</span>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalHours }}</div>
            <div class="stat-label">小时</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="stat-header">
              <el-icon><Medal /></el-icon>
              <span>完成课程</span>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.completedCourses }}</div>
            <div class="stat-label">门课程</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <template #header>
            <div class="stat-header">
              <el-icon><Trophy /></el-icon>
              <span>获得证书</span>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.certificates }}</div>
            <div class="stat-label">张证书</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习进度列表 -->
    <el-card class="progress-list" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <h2>课程学习进度</h2>
          <el-input
            v-model="searchQuery"
            placeholder="搜索课程"
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="courseList"
        style="width: 100%"
      >
        <el-table-column label="课程信息" min-width="300">
          <template #default="{ row }">
            <div class="course-info">
              <el-image 
                :src="row.cover" 
                class="course-cover"
                fit="cover"
              />
              <div class="course-detail">
                <h3>{{ row.title }}</h3>
                <p>{{ row.teacher }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="学习进度" width="200">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.progress"
              :format="format"
              :status="row.isLearning ? 'success' : 'warning'"
            />
          </template>
        </el-table-column>
        <el-table-column label="学习时长" width="120">
          <template #default="{ row }">
            {{ row.totalDuration }}h
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              :type="row.isLearning ? 'warning' : 'success'" 
              @click="toggleLearning(row)"
            >
              {{ row.isLearning ? '暂停学习' : '继续学习' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Reading, 
  Timer, 
  Medal, 
  Trophy, 
  Search 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 统计数据
const stats = computed(() => {
  const learningCourses = filteredCourses.value.filter(course => course.progress < 100).length;
  const completedCourses = filteredCourses.value.filter(course => course.progress === 100).length;
  const totalHours = filteredCourses.value.reduce((sum, course) => sum + course.totalDuration, 0);
  return {
    learningCourses,
    completedCourses,
    totalHours: parseFloat(totalHours.toFixed(2)), // 保留两位小数
    certificates: 2 // 证书数量暂时保留模拟数据，因为没有相关逻辑
  };
});

// 搜索
const searchQuery = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 过滤后的课程列表 (用于统计和分页)
const filteredCourses = ref([]);

// 课程列表 (用于当前页显示)
const courseList = ref([])

// 获取课程列表
const fetchCourseList = async () => {
  loading.value = true
  try {
    // 优先从 localStorage 中读取数据
    const savedCourses = localStorage.getItem('learningProgress');
    let mockData;
    
    if (savedCourses) {
      mockData = JSON.parse(savedCourses);
    } else {
      // 如果没有保存的数据，则使用模拟数据
      mockData = Array.from({ length: 20 }, (_, index) => ({
        id: index + 1,
        title: `课程${index + 1}`,
        teacher: `讲师${index + 1}`,
        cover: `https://picsum.photos/300/200?random=${index}`,
        level: ['初级', '中级', '高级'][index % 3],
        rating: Math.floor(Math.random() * 3) + 3,
        progress: Math.floor(Math.random() * 100),
        isLearning: false,
        totalDuration: 0 // 初始学习时长为0
      }));
      // 首次加载时保存到 localStorage
      localStorage.setItem('learningProgress', JSON.stringify(mockData));
    }
    
    // 模拟搜索
    let filteredData = mockData;
    if (searchQuery.value) {
      filteredData = mockData.filter(course => 
        course.title.includes(searchQuery.value) ||
        course.teacher.includes(searchQuery.value)
      );
    }
    
    // 保存完整的过滤后数据
    filteredCourses.value = filteredData;

    total.value = filteredData.length;
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    // 只将当前页数据赋值给courseList用于显示
    courseList.value = filteredData.slice(start, end);
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCourseList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCourseList()
}

// 格式化进度
const format = (percentage) => {
  return percentage === 100 ? '已完成' : `${percentage}%`
}

// 获取难度等级标签类型
const getLevelType = (level) => {
  const types = {
    '初级': 'success',
    '中级': 'warning',
    '高级': 'danger'
  };
  return types[level] || 'info';
};

// 切换学习状态
const toggleLearning = (course) => {
  // 如果当前是"继续学习"状态且progress小于100
  if (!course.isLearning && course.progress < 100) {
    // 每次点击"继续学习"，学习时长增加1小时
    course.totalDuration += 1;
    // 模拟进度增加（例如每次学习1小时，进度增加10%）
    course.progress = Math.min(100, course.progress + 10);

    // 学习状态设为true（表示正在学习，尽管这里是单次增加）
    course.isLearning = true;

    ElMessage.success(`学习时长 +1h！ ${course.title}`);

    // 更新localStorage中的数据
    updateCourseProgressInStorage(course);

    // 如果进度达到100%，显示完成提示并可能禁用按钮
    if (course.progress === 100) {
       ElMessage.success(`课程完成：${course.title}`);
       // 可以选择在这里将isLearning设回false或者添加一个isCompleted状态
       course.isLearning = false; // 课程完成则不再显示暂停/继续
    }

  } else if (course.isLearning && course.progress < 100) { // 如果当前是"暂停学习"状态且未完成
    // 如果您希望"暂停学习"按钮有实际暂停计时器的功能，需要保留计时器逻辑
    // 根据您"学习一次加1h"的需求，这里点击暂停学习可能只是状态切换或者不进行任何操作
    // 如果只是状态切换，可以将isLearning设回false
     course.isLearning = false;
     ElMessage.warning(`暂停学习：${course.title}`);
     // 更新localStorage中的数据
     updateCourseProgressInStorage(course);
  } else if (course.progress === 100) {
      // 如果课程已完成，点击按钮不进行任何操作或给出提示
      ElMessage.info(`课程已完成：${course.title}`);
  }

};

// 更新localStorage中的数据
const updateCourseProgressInStorage = (course) => {
  const savedCourses = localStorage.getItem('learningProgress');
  if (savedCourses) {
    const courses = JSON.parse(savedCourses);
    const index = courses.findIndex(item => item.id === course.id);
    if (index !== -1) {
      courses[index] = course;
      localStorage.setItem('learningProgress', JSON.stringify(courses));
    }
  }
};

// Function to reset durations except for Course 2
const resetDurationsExceptCourse2 = () => {
  const savedCourses = localStorage.getItem('learningProgress');
  if (savedCourses) {
    const courses = JSON.parse(savedCourses);
    courses.forEach(course => {
      // 根据课程标题判断是否为"课程2"
      if (course.title !== '课程2') {
         course.totalDuration = 0;
         // 如果需要，也可以在这里重置进度
         // course.progress = 0;
      }
    });
    localStorage.setItem('learningProgress', JSON.stringify(courses));
    console.log('学习时长已重置（课程2除外）');
    // 更新当前显示的列表，触发计算属性重新计算
    fetchCourseList();
  }
};

// Function to set Course 2 duration to 8 hours
const setCourse2DurationTo8Hours = () => {
  const savedCourses = localStorage.getItem('learningProgress');
  if (savedCourses) {
    const courses = JSON.parse(savedCourses);
    const course2 = courses.find(course => course.title === '课程2');
    if (course2) {
      course2.totalDuration = 8;
      // Optional: set progress to a value corresponding to 8 hours if total duration is known
      // For example, if total duration is 100 hours, 8 hours is 8%
      // course2.progress = (8 / totalCourse2Duration) * 100;
      // Or set it to 100 if it's completed
      // course2.progress = 100;

      localStorage.setItem('learningProgress', JSON.stringify(courses));
      console.log('课程2学习时长已设置为8小时');
      // 更新当前显示的列表，触发计算属性重新计算
      fetchCourseList();
    }
  }
};

onMounted(() => {
  fetchCourseList();
  // 在加载数据后执行一次设置课程2时长的操作
  setCourse2DurationTo8Hours();
  // 如果需要，可以在这里保留之前的重置所有课程时长的函数调用
  // resetDurationsExceptCourse2();
})
</script>

<style scoped>
.learning-progress {
  padding: 20px;
}

.stat-card {
  height: 100%;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-secondary);
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.stat-label {
  color: var(--el-text-color-secondary);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.search-input {
  width: 300px;
}

.course-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.course-cover {
  width: 80px;
  height: 45px;
  border-radius: 4px;
}

.course-detail h3 {
  margin: 0 0 5px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.course-detail p {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 